/**
 * Created by Kpeng on 2017/7/3.
 * Depending on the jquery-1.12.4.min.js.
 * Depending on the common.js.
 * Depending on the style.min.css.
 * To cite this document, always state the source as shown above.
 * -------------------------------
 * Module:数据词典
 * -------------------------------
 */
$(function () {
  wzERP.Dict.init();
});

wzERP.Dict.init = function () {
  wzERP.Dict.addType(); //添加词典类型
  wzERP.Dict.delTypeHandle();
  wzERP.Dict.addHandle();
  wzERP.Dict.editHandle()
  // wzERP.Dict.delHandle();
  wzERP.Dict.turnPage();//分页

};

//添加词典类型
wzERP.Dict.addType = function () {
  var opt = {
    ele: '.addType',
    modalBox: '#modal',
    modalTitleStr: '添加词典类别',
    onApprove: function () {
      if (wzERP.Dict.isExistTypeHandle()) {
        return false;
      }
      wzERP.Common.saveHandle('#addDictTypeForm', '#addDictTypeUrl',
          $(this).find('.setId'), '',
          wzERP.Common.delayReload(wzERP.delayTime));
    },
    snippets: $("#addOrEditDictTypeHtml").val()
  };
  wzERP.Common.handleData(opt);
};
wzERP.Dict.isExistTypeHandle = function () {
  //校验ID唯一
  var name = $("#addDictTypeForm").find("[name='name']").val();
  var nameOrg = $("#addDictTypeForm").find("[name='nameOrg']").val();
  if (nameOrg != name) {
    var flag = false;
    //判断类型名称是否存在
    var url = $("#isExistDictTypeUrl").val();
    $.ajax({
      type: "GET",
      url: url,
      data: 'name=' + name,
      async: false,
      dataType: 'json',
      success: function (data) {
        switch (data.data) {
          case 1:
            layer.msg('类型名称已存在', {icon: 2, time: 1000});
            flag = true;//存在
            break;
          default:
            flag = false;//不存在
        }
      }
    });
    return flag;
  }
};

//删除词典类别
wzERP.Dict.delTypeHandle = function () {

  /*var opt = {
   ele: '.delBtn',
   modalBox: '#modal',
   modalTitleStr: '',
   onApprove: function () {
   wzERP.Common.deleteData('#deleteDictTypeUrl', $(this).find('.setId'));
   },
   snippets: $("#deleteDictTypeHtml").val()
   };
   wzERP.Common.handleData(opt);*/

  $('#main').on('click', '.delBtn', function () {
    var $self = $(this);
    layer.alert('确定删除该数据词典吗？', {
          title: '提示信息',
          btn: ['取消', '确认'],
          btn1: function (index) {
            layer.close(index)
          },
          btn2: function () {
            wzERP.Common.deleteData('#deleteDictTypeUrl', $self)
          }
        }
    );
  })
};

//编辑词典
wzERP.Dict.editHandle = function () {
  var opt = {
    ele: '.editBtn',
    modalBox: '#modal',
    modalTitleStr: '编辑词典类别',
    onApprove: function () {
      if (wzERP.Dict.isExistTypeHandle()) {
        return false;
      }
      wzERP.Common.saveHandle('#addDictTypeForm', '#editDictTypeUrl',
          $(this).find('.setId'), wzERP.Common.delayReload(wzERP.delayTime));
    },
    // snippets: '/dicttionary/update/dict-addType.html'
    snippets: $("#addOrEditDictTypeHtml").val()
  };
  wzERP.Dict.handleData(opt);
};

//添加词典
wzERP.Dict.addHandle = function () {
  var opt = {
    ele: '.addBtn',
    modalBox: '#modal',
    modalTitleStr: '添加词典',
    onApprove: function () {
    },
    snippets: $("#addDictDetailHtml").val()
  };
  wzERP.Common.handleData(opt);
};

//添加子词典数据
wzERP.Dict.addChildHanlde = function (id) {
  // debugger
  var opt = {
    template: '#temp',
    container: "#childDictList tbody",
    wrapper: "#modalContent",
    submitForm: "#submitForm",
    addBtn: '.addDictBtn',
    addChildBtn: '.addChildBtn',
    saveBtn: ".saveDictBtn",
    editBtn: ".editDictBtn",
    // delBtn: ".delDictBtn",
    cancelBtn: ".cancelDictBtn2",
    saveFn: function () {
      var curRow = this.event.parents('tr'),
          selfId = curRow.data('id') || '',//自身ID
          parentId = curRow.data('pid'),  //父级ID
          typeId = curRow.data('type') || '',   //类别ID
          dictionaryDetailName = curRow.find(
              'input[name=dictionaryDetailName]').val(),  //字典名称
          dictionaryDetailValue = curRow.find(
              'input[name=dictionaryDetailValue]').val(), //键值
          dictionaryDetailKey = curRow.find(
              'input[name=dictionaryDetailKey]').val(), //键名
          display = curRow.find('input[name=show]').prop('checked'),
          opt = {
            url: "#addOrUpdateDictDetailUrl",
            param: {
              id: selfId,
              detailParentId: parentId,
              dataDictionaryId: typeId,
              dictionaryDetailName: dictionaryDetailName,
              dictionaryDetailValue: dictionaryDetailValue,
              dictionaryDetailKey: dictionaryDetailKey,
              display: display
            },
            successFn: function () {
              curRow.attr('data-id', this.newId);
              curRow.find('.saveDictBtn').attr('data-id', this.newId);
            },
            errorFn: function () {
              curRow.addClass('editing');
            }
          };
      wzERP.Common.saveAjaxHandle(opt);
    },
    delFn: function () {
      var curRow = this.event.parents('tr'),
          rowLen = curRow.siblings().length,
          param = {id: this.ids};
      $.post($("#dictItemDelete").val(), param, function (data) {
            switch (data.code) {
              case 0:
                layer.msg(data.msg, {icon: 7, time: 1000});  //成功
                curRow.remove();
                if (rowLen === 0) {
                  wzERP.Common.delayReload(200);
                }
                break;
              case 1:
                layer.msg(data.msg, {icon: 5, time: 1000}); //失败
                break;
              default:
                layer.msg(data.msg, {icon: 2, time: 1000});  //默认
            }
            return false;
          },
          'json');
    },
  };
  wzERP.Common.editTable(opt);
};

//删除词典
/*wzERP.Dict.delHandle = function () {
 var opt = {
 ele: '.delBtn',
 modalBox: '#modal',
 modalTitleStr: '',
 onApprove: function () {
 wzERP.Common.deleteData('#deleteDictTypeUrl', $(this.modalBox).find('.setId'));
 },
 snippets: $('#deleteDictTypeHtml').val()
 };
 wzERP.Common.handleData(opt);
 };*/

//分页跳转
wzERP.Dict.turnPage = function () {
  var opt = {
    pageUrl: $("#dictionaryPageUrl").val(),
    pageSearch: "#searchForm",
    pagesTotal: parseInt($('#pages').val()),
    pageCurr: parseInt($('#current').val()),
    pageSize: parseInt($('#pageSize').val()),
    currId: "#current"
  };
  wzERP.Common.pagingHandle(opt);
};

//
function search() {
  $("#current").val(1);
  $("#searchForm").action = "/dicttionary/queryByPage";
  $("#searchForm").submit();
}

//激活状态
wzERP.Dict.isActive = function () {
  var actives = $('#childDictList').find('.toggle').find('input');
  actives.on('click', function () {
    var active = $(this).prop('checked')
    var url = $('#changeAcitveUrl').val();
    var params = {
      id: $(this).parent().data('id') || "",
      display: active

    }
    if (params.id !== "") {
      $.post(url, params, function (data) {
        switch (data.status) {
          case 0:
            layer.msg(data.msg, {icon: 2, time: 1000});  //成功
            break;
          case 1:
            layer.msg(data.msg, {icon: 5, time: 1000}); //失败
            wzERP.Common.delayReload(500);
            break;
          default:
            layer.msg(data.msg, {icon: 7, time: 1000});  //默认
        }
      }, 'json')
    }

  });
};

wzERP.Dict.showCancleBtn = function () {
  var rows = $('#modalContent').find('.row-item');
  if (rows.length === 1 && rows.hasClass('new')) {
    rows.find('.cancelDictBtn2').hide()
  }
};

//表单验证器
wzERP.Dict.verifier = function (_selector) {
  /*Arg Guide
   @_selector: 对象选择器
   */
  $(_selector).form({
    on: 'blur',
    // inline: true,
    transition: 'fade',
    fields: {
      //类别名称
      name: {
        identifier: 'name',
        rules: [{
          type: 'empty',
          prompt: '请输类别名称'
        }
        ]
      },
      //Code
      code: {
        identifier: 'code',
        rules: [{
          type: 'empty',
          prompt: '请输入Code'
        },
          {
            type: 'regExp[/^[a-z]+$/i]',
            prompt: 'Code必须为纯字母格式'
          },
          {
            type: 'regExp[/^.{0,30}$/]',
            prompt: 'Code必须为30字以内'
          }
        ]
      },
      //词典名称
      dictionaryDetailName: {
        identifier: 'dictionaryDetailName',
        rules: [{
          type: 'empty',
          prompt: '请输入词典名称'
        },
          {
            type: 'regExp[/^[^\\s]{1,40}$/]',
            prompt: '词典名称字数限制40字'
          }]
      },
      //键名
      dictionaryDetailKey: {
        identifier: 'dictionaryDetailKey',
        rules: [{
          type: 'empty',
          prompt: '请输入键名'
        },
          {
            type: 'regExp[/^[a-zA-Z]{1,40}$/]',
            prompt: 'Code必须为纯字母格式'
          }]
      },
      //键值
      dictionaryDetailValue: {
        identifier: 'dictionaryDetailValue',
        rules: [{
          type: 'empty',
          prompt: '请输入键值'
        },
          {
            type: 'regExp[/^\\d{1,2}$/]',
            prompt: '键值必须为两位以内数字'
          }]
      },
      //desc
      desc: {
        identifier: 'desc',
        rules: [
          {
            type: 'regExp[/^.{0,50}$/]',
            prompt: '说明字数限制50字'
          }]
      }
    }
  });

};

//模态框响应
wzERP.Dict.handleData = function (_option) {
  /*Arg Guide
   @ option.ele:触发元素
   @ option.modal:模态框元素
   @ option.onApprove:“保存/确定”事件函数
   @ option.snippets:模态框内容代码片段路由
   @ option.callback:回调函数
   */

  $('#main').on('click', _option.ele, function () {
    var btnType = $(this).data('type'),  //获取挂载
        modalBox = $(_option.modalBox),
        modalHeader = modalBox.find('.header'),
        isDelete = btnType === 'delete',
        isAdd = btnType === 'add',
        getId = $(this).data('id') || ""; //获取ID ;
    //更改模态框类型
    isDelete ? modalBox.addClass('basic') : modalBox.removeClass('basic');
    _option.event = $(this);
    //将触发按钮的id绑定到模态框确定按钮上
    if (getId) {
      modalBox.find('.setId').attr('data-id', isAdd ? '' : getId);
    }
    modalBox.modal({
      closable: false,
      transition: 'fade',
      onDeny: function () {
        // 拒绝或取消
        //alert('拒绝了拒绝了拒绝了拒绝了!');
      },
      onHidden: function () {
        //关闭模态框
        $('#modal').removeAttr('style');
      },
      onApprove: function () {
        var isPass = true,
            requiredHooks = modalBox.find('.required-hook');

        //验证必填项是否符合规则
        requiredHooks.each(function () {
          var _this = $(this),
              isPrompt = _this.siblings('.prompt').length; //判断是否有未保存必填项

          console.log(this.value, this.nodeName, $(this).attr('id'));
          var id = $(this).attr('id');
          if (!this.value || isPrompt) {  //当表单为空并且有报错
            if (id == 'addCmpAddPage' || id == 'addDepartAddPage' || id
                == 'addJobAddPage') { //排除兼岗位置不通过问题
              isPass = true;
              if (this.nodeName === 'SELECT') {
                _this.parent('.dropdown').removeClass('error');
              }
              return true;
            }
            isPass = false;
            if (this.nodeName === 'SELECT') {
              _this.parent('.dropdown').addClass('error');
            } else {
              _this.parent('.required').addClass('error');
            }
            if (!this.value) {
              layer.msg('必选项不能留空白', {icon: 2});
              return false;
            }
            layer.msg('填写项不符合规则', {icon: 2});
            return false;
          } else {
            isPass = true;
            if (this.nodeName === 'SELECT') {
              _this.parent('.dropdown').removeClass('error');
            }
            return true;
          }
        });
        if (isPass && _option.onApprove instanceof Function) {
          var flag = _option.onApprove();
          if (flag === false) {
            return false;
          }
          else {
            //console.info("option.onApprove()="+flag);
          }
        } else {
          return false;
        }
      }
    }).modal('show');
    modalHeader.empty().prepend(
        '<i class="warning circle icon red"></i><span>' + _option.modalTitleStr
        + '</span>');
    isDelete ? modalHeader.addClass('del-modal-header')
        : modalHeader.removeClass('del-modal-header');
    if (_option.callback instanceof Function) {
      _option.callback();
    }
    if (_option.url) {
      _option.snippets = _option.url;
      console.log(_option.url);
    }
    wzERP.Dict.loadHtml(wzERP.ViewDir + _option.snippets + "?id=" + getId,
        '#modalContent');
    console.log(wzERP.ViewDir + _option.snippets + "?id=" + getId)
  });
};

//利用Modal动态装载其它页面Dom
wzERP.Dict.loadHtml = function (_snippetsDir, _target, _callback) {
  /*Arg Guide
   @_snippets: 需要load进来的代码片段
   @_target: 需要load进的目标容器
   @_callback: 回调事件函数
   */
  $.ajaxSetup({
    cache: false //关闭AJAX相应的缓存
  });
  $(_target).empty().load(_snippetsDir, function () {
    setTimeout(function () {
      // $("#dicCode").attr("readonly",true)
      document.getElementById("dicCode").readOnly = true;
    }, 0)
  });
  /*if (_callback instanceof Function) {
   setTimeout(_callback(), 300);
   }*/
};